import {
  getActivityOrgListService,
  getActivityOrgInfoService,
  getOrgGroupListService,
  getProductByGroupService,
  getOrgDiscountGroupListService,
  getDiscountProductByGroupService,
  getProductCarListService,
  addProductToCarService,
  storeCategoryServer,
  getDiscountProductTotalServer,
  getProductDetailServer,
} from '@/services/takeOut';
import { topOrgListService } from '@/services/otherApi';
import Taro from '@tarojs/taro';
import { dealPayloadParams } from './commonFunc';

export default {
  namespace: 'takeOut',
  state: {
    // 获取店铺分类
    storeCategory: [],

    takeOutCartShop: [],
    //首页外卖商户列表
    takeOutOrgParams: {},
    takeOutOrgList: [],
    takeOutOrgFinished: false,
    //独立分类外卖商户列表页
    takeOutItemOrgParams: {},
    takeOutItemOrgList: [],
    takeOutItemOrgPagination: {},
    takeOutItemOrgFinished: false,
    //外卖店铺分组列表
    takeOutProductsParams: {},
    takeOutProductsList: null,
    //外卖商品详情
    takeOutProductDetail: [],
  },
  effects: {
    // 获取店铺分类
    *fetchStoreCategory({ payload }, { call, put }) {
      yield put({
        type: 'setStoreCategory',
        payload: [],
      });

      const res = yield call(storeCategoryServer, payload);
      if (res.code !== '1') {
        Taro.showToast({
          title: res.message,
          duration: 1000,
          icon: 'none',
        });
        return Promise.reject();
      }
      res.content?.length > 0 &&
        res.content?.map((item) => {
          item.industryDetailResponses.unshift({
            secondIndustryId: 0,
            secondIndustryName: '全部',
          });
        });

      const list = [{ firstIndustryName: '全部分类', firstIndustryId: 0 }, ...res.content];

      yield put({
        type: 'setStoreCategory',
        payload: list,
      });

      return list;
    },

    //店铺列表
    *getActivityOrgListModel({ payload }, { call }) {
      const res = yield call(getActivityOrgListService, payload);
      if (res.code === '1') {
        return res.content;
      }
    },

    //店铺详情
    *getActivityOrgInfoModel({ payload }, { call }) {
      const res = yield call(getActivityOrgInfoService, payload);
      if (res.code === '1') {
        return res.content;
      }
    },

    //店铺商品分组标签
    *getOrgGroupListModel({ payload }, { call }) {
      const res = yield call(getOrgGroupListService, payload);
      if (res.code === '1') {
        return res.content;
      }
    },

    //根据标签查找商品
    *getProductByGroupModel({ payload }, { call }) {
      const res = yield call(getProductByGroupService, payload);
      if (res.code === '1') {
        return res.content;
      }
    },

    //折扣店铺商品分组标签
    *getOrgDiscountGroupListModel({ payload }, { call }) {
      const res = yield call(getOrgDiscountGroupListService, payload);
      if (res.code === '1') {
        return res.content;
      }
    },

    //折扣根据标签查找商品
    *getDiscountProductByGroupModel({ payload }, { call }) {
      const res = yield call(getDiscountProductByGroupService, payload);
      if (res.code === '1') {
        return res.content;
      }
    },

    //外卖查询购物车商品列表
    *getProductCarListModel({ payload }, { call }) {
      const res = yield call(getProductCarListService, payload);
      if (res.code === '1') {
        return res.content;
      } else {
        return [];
      }
    },

    //商品加入购物车
    *addProductToCarModel({ payload }, { call, put }) {
      const res = yield call(addProductToCarService, payload);
      if (res.code === '1') {
        // 重新获取购物车数量
        yield put({ type: 'productList/getCarNum', payload: {} });

        return 'success';
      } else {
        return 'fail';
      }
    },

    // 首页外卖安心到家店铺列表
    *getTakeOutOrgListModel({ payload }, { select, call, put }) {
      const params = yield select(({ takeOut }) => takeOut.takeOutOrgParams);
      const curIsFinished = yield select(({ takeOut }) => takeOut.takeOutOrgFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(topOrgListService, payload);
      if (res.code == 1) {
        const list = res.content || [];
        let dataList = [];
        if (payload.page != 1) {
          const curDataList = yield select(({ takeOut }) => takeOut.takeOutOrgList);
          dataList = [...curDataList, ...list];
        } else {
          dataList = [...list];
        }
        let isFinished = false;
        if (list.length < payload.pageSize) {
          isFinished = true;
        }
        yield put({
          type: 'setTakeOutList',
          payload: {
            takeOutOrgList: dataList,
            takeOutOrgParams: { ...payload },
            takeOutOrgFinished: isFinished,
          },
        });
      } else {
        Taro.showToast({
          title: '获取外卖商户数据失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    // 分类外卖店铺列表独立页
    *getTakeOutItemOrgListModel({ payload }, { select, call, put }) {
      const params = yield select(({ takeOut }) => takeOut.takeOutItemOrgParams);
      const curIsFinished = yield select(({ takeOut }) => takeOut.takeOutItemOrgFinished);

      const isAlreadyFinished = dealPayloadParams(payload, params, curIsFinished);
      if (isAlreadyFinished) {
        return;
      }

      const res = yield call(getActivityOrgListService, payload);
      if (res.code == 1) {
        const { list, pagination } = res.content;
        let dataList = [];
        if (payload.page != 1) {
          const curDataList = yield select(({ takeOut }) => takeOut.takeOutItemOrgList);
          dataList = [...curDataList, ...list];
        } else {
          dataList = [...list];
        }
        let isFinished = false;
        if (dataList.length >= pagination.totalCount) {
          isFinished = true;
        }
        yield put({
          type: 'setTakeOutItemList',
          payload: {
            takeOutItemOrgList: dataList,
            takeOutItemOrgPagination: { ...pagination },
            takeOutItemOrgParams: { ...payload },
            takeOutItemOrgFinished: isFinished,
          },
        });
      } else {
        Taro.showToast({
          title: '获取商户数据失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    //获取外卖店铺分组和商品
    *getDiscountProductTotalModel({ payload }, { call, put, select }) {
      const params = yield select(({ takeOut }) => takeOut.takeOutProductsParams);
      if (params?.merchantId !== payload.merchantId || params?.orgId !== payload.orgId) {
        yield put({
          type: 'setTakeOutProducts',
          payload: {
            takeOutProductsList: null,
            takeOutProductsParams: {},
          },
        });
      }
      const res = yield call(getDiscountProductTotalServer, payload);
      if (res.code === '1') {
        yield put({
          type: 'setTakeOutProducts',
          payload: {
            takeOutProductsList: [...res.content],
            takeOutProductsParams: { ...payload },
          },
        });
      } else {
        Taro.showToast({
          title: '获取外卖店铺商品失败',
          duration: 2000,
          icon: 'none',
        });
      }
    },

    *getProductDetailModel({ payload }, { call, put }) {
      const res = yield call(getProductDetailServer, payload);
      if (res.code == 1) {
        let optionObj = res.content.option ? JSON.parse(res.content.option) : {};
        let optionsObj = res.content.options ? JSON.parse(res.content.options) : {};
        let defaultOption = [];
        let defaultOptionForSku = [];
        let isMutilSku = false;
        for (let key in optionObj) {
          defaultOption.push(optionObj[key]);
          defaultOptionForSku.push({ name: key, value: optionObj[key] });
        }
        for (let key in optionsObj) {
          if (optionsObj[key].length > 1) {
            isMutilSku = true;
            break;
          }
        }
        res.content.isMutilSku = isMutilSku;
        res.content.optionStr = defaultOption.join('/');
        res.content.defaultOptionForSku = defaultOptionForSku;
        res.content.optionsObj = optionsObj;
        yield put({
          type: 'setProductDetailList',
          payload: {
            takeOutProductDetail: { ...res.content },
          },
        });
      } else {
        Taro.showToast({
          title: '获取外卖商品详情失败',
          duration: 1000,
          icon: 'none',
        });
      }
    },

    *refreashProductDetailModel({ payload }, { select, put }) {
      const theProductDetail = yield select(({ takeOut }) => takeOut.takeOutProductDetail);
      yield put({
        type: 'setProductDetailList',
        payload: {
          takeOutProductDetail: { ...theProductDetail, ...payload },
        },
      });
    },
  },
  reducers: {
    // 获取店铺分类
    setStoreCategory(state, { payload }) {
      return {
        ...state,
        storeCategory: payload,
      };
    },

    setTakeOutCartShopList(state, { payload }) {
      let { proIdListInCartShop } = payload;
      return {
        ...state,
        takeOutCartShop: [...proIdListInCartShop],
      };
    },
    setTakeOutList(state, { payload }) {
      const { takeOutOrgList, takeOutOrgParams, takeOutOrgFinished } = payload;
      return {
        ...state,
        takeOutOrgList,
        takeOutOrgParams,
        takeOutOrgFinished,
      };
    },
    setTakeOutItemList(state, { payload }) {
      const {
        takeOutItemOrgList,
        takeOutItemOrgPagination,
        takeOutItemOrgParams,
        takeOutItemOrgFinished,
      } = payload;
      return {
        ...state,
        takeOutItemOrgList,
        takeOutItemOrgPagination,
        takeOutItemOrgParams,
        takeOutItemOrgFinished,
      };
    },
    setTakeOutProducts(state, { payload }) {
      let { takeOutProductsList, takeOutProductsParams } = payload;
      return {
        ...state,
        takeOutProductsList,
        takeOutProductsParams,
      };
    },
    setProductDetailList(state, { payload }) {
      let { takeOutProductDetail } = payload;
      return {
        ...state,
        takeOutProductDetail,
      };
    },
  },
};
